package com.qingcheng.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.AdminMapper;
import com.qingcheng.dao.AdminRoleMapper;
import com.qingcheng.dao.RoleMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.system.Admin;
import com.qingcheng.pojo.system.AdminRole;
import com.qingcheng.pojo.system.Role;
import com.qingcheng.pojo.system.WholeAdmin;
import com.qingcheng.service.system.AdminService;
import com.qingcheng.utils.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service(interfaceClass =AdminService.class )
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private RoleMapper roleMapper;





    /**
     * 返回全部记录
     * @return
     */
    public List<Admin> findAll() {
        return adminMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Admin> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Admin> admins = (Page<Admin>) adminMapper.selectAll();
        return new PageResult<Admin>(admins.getTotal(),admins.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Admin> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return adminMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Admin> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Admin> admins = (Page<Admin>) adminMapper.selectByExample(example);
        return new PageResult<Admin>(admins.getTotal(),admins.getResult());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public Admin findById(Integer id) {
        return adminMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     * @param admin
     */
    public void add(Admin admin) {
        adminMapper.insert(admin);
    }

    /**
     * 修改
     * @param admin
     */
    public void update(Admin admin) {
        adminMapper.updateByPrimaryKeySelective(admin);
    }

    /**
     *  删除
     * @param id
     */
    public void delete(Integer id) {
        adminMapper.deleteByPrimaryKey(id);
    }

    /**
     * 定义修改密码的方法
     * @param map
     */
    @Override
    @Transactional
    public void editPassword(Map<String, String> map) {
        //获取参数
        String loginName = map.get("username");
        String oldPassword = map.get("oldPassword");
        String newPassword = map.get("newPassword");
        String checkPassword = map.get("checkPassword");
        //比对新旧密码
        if(!newPassword.equals(checkPassword)){
            throw new RuntimeException("请输入相同的密码");
        }
        //根据username查询
        Example example=new Example(Admin.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("loginName",loginName);
        List<Admin> adminList = adminMapper.selectByExample(example);
        Admin admin = adminList.get(0);
        //验证密码
        boolean flag = BCrypt.checkpw(oldPassword, admin.getPassword()); //验证加密后的密码
        if(!flag){
            throw new RuntimeException("输入的原密码有误");
        }
        //将新密码存入数据库
        String gensalt = BCrypt.gensalt(); //加盐
        String oldPassword1 = BCrypt.hashpw(newPassword, gensalt); //将前台输入的密码加密
        //设置用户密码
        admin.setPassword(oldPassword1);
        adminMapper.updateByPrimaryKeySelective(admin);
    }

    /**
     * 定义查询用户带着角色的方法
     * @return
     */
    @Override
    public List<WholeAdmin> findWholeAdmin() {
        //创建集合作为返回值
        List<WholeAdmin> list=new ArrayList<WholeAdmin>();
        //查询所有用户信息
        List<Admin> adminList = adminMapper.selectAll();
        if(adminList.size()!=0){
            //遍历集合用户的集合
            for (Admin admin : adminList) {
                //创建对象
                WholeAdmin wholeAdmin=new WholeAdmin();
                //获取用户对象的Id
                Integer id = admin.getId();
                //根据Id查询对应的角色集合
                List<Role> roleList = adminMapper.findRoleList(id);
                //封装对象
                wholeAdmin.setAdmin(admin);
                wholeAdmin.setRoleList(roleList);
                list.add(wholeAdmin);
            }
        }
        return list;
    }

    /**
     * 定义新增用户和角色的方法
     * @param wholeAdmin
     */
    @Override
    @Transactional
    public void addWholeAdmin(WholeAdmin wholeAdmin) {
        //获取用户信息
        Admin newAdmin = wholeAdmin.getAdmin();

        //判断用户名是否重复
        List<Admin> adminList = adminMapper.selectAll();
        for (Admin admin : adminList) {
            if(newAdmin.getLoginName().equals(admin.getLoginName())){
                throw new RuntimeException("用户名重复");
            }
        }

        //对密码进行加密
        String gensalt = BCrypt.gensalt(); //加盐
        //对密码进行加密
        String password = BCrypt.hashpw(newAdmin.getPassword(), gensalt);
        newAdmin.setPassword(password);

        //存入用户信息
        adminMapper.insert(newAdmin);

        //获取用户存入是的id值
        Integer adminId = newAdmin.getId();

        //判断角色集合是否为空
        List<Role> roleList = wholeAdmin.getRoleList();
        if(roleList.size()!=0){
            //遍历存入集合
            for (Role role : roleList) {
                //创建角色和用户的联合主键对象
                AdminRole adminRole=new AdminRole();
                adminRole.setAdminId(adminId);
                adminRole.setRoleId(role.getId());
                //存入数据库
                adminRoleMapper.insert(adminRole);
            }
        }
    }

    /**
     * 定义修改用户的方法
     * @param wholeAdmin
     */
    @Override
    @Transactional
    public void updateWholeAdmin(WholeAdmin wholeAdmin) {
        //获取admin值
        Admin admin = wholeAdmin.getAdmin();
        //获取adminId
        Integer adminId = admin.getId();
        //删除输出admin_role表中的数据
        Example example=new Example(AdminRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("adminId",adminId);
        adminRoleMapper.deleteByExample(example);

        //根据id查询出原来的用户,比对密码是否修改了
        Admin oldAdmin = adminMapper.selectByPrimaryKey(adminId);
        if(!oldAdmin.getPassword().equals(admin.getPassword())){
            //输入的是新的密码，加密存入
            String password = admin.getPassword();
            String gensalt = BCrypt.gensalt(); //加盐
            String newPassword = BCrypt.hashpw(password, gensalt);
            admin.setPassword(newPassword);
        }
        //将用户信息存入数据库
        adminMapper.updateByPrimaryKeySelective(admin);

        //遍历集合，将数据逐条添加
        List<Role> roleList = wholeAdmin.getRoleList();
        if (roleList.size()!=0){
            for (Role role : roleList) {
                AdminRole adminRole=new AdminRole();
                adminRole.setAdminId(adminId);
                adminRole.setRoleId(role.getId());
                //将数据存入数据库
                adminRoleMapper.insert(adminRole);
            }
        }
    }

    /**
     * 定义根据id查询的方法
     * @param id
     * @return
     */
    @Override
    @Transactional
    public WholeAdmin findWholeAdminById(Integer id) {
        //根据id查询Admin对象
        Admin admin = adminMapper.selectByPrimaryKey(id);
        //根据id查询Role集合
        List<Role> roleList = adminMapper.findRoleList(id);
        //封装进WholeAdmin对象中
        WholeAdmin wholeAdmin=new WholeAdmin();
        wholeAdmin.setAdmin(admin);
        wholeAdmin.setRoleList(roleList);
        return wholeAdmin;
    }

    /**
     * 定义删除用户及其角色的方法
     * @param id
     */
    @Override
    @Transactional
    public void deleteWholeAdmin(Integer id) {
        //根据id删除用户
        adminMapper.deleteByPrimaryKey(id);
        //删除用户角色
        Example example=new Example(AdminRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("adminId",id);
        adminRoleMapper.deleteByExample(example);

    }

    /**
     * 定义根据用户id查询所有资源的方法
     * @param id
     * @return
     */
    @Override
    public List<String> findAllResourceId(Integer id) {
        return adminMapper.findAllResourceById(id);
    }

    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Admin.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 用户名
            if(searchMap.get("loginName")!=null && !"".equals(searchMap.get("loginName"))){
               // criteria.andLike("loginName","%"+searchMap.get("loginName")+"%");
                criteria.andEqualTo("loginName",searchMap.get("loginName"));
            }
            // 密码
            if(searchMap.get("password")!=null && !"".equals(searchMap.get("password"))){
                criteria.andLike("password","%"+searchMap.get("password")+"%");
            }
            // 状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andLike("status","%"+searchMap.get("status")+"%");
            }

            // id
            if(searchMap.get("id")!=null ){
                criteria.andEqualTo("id",searchMap.get("id"));
            }

        }
        return example;
    }

}
